package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.RatingDTO;
import com.lastproject.ejb.entities.Rating;
import com.lastproject.ejb.util.RatingConversion;



/**
 * Session Bean implementation class RatingDAO
 * author: Lia Sincari
 */
@Stateless
public class RatingDAO implements RatingDAORemote {

    /**
     * Default constructor. 
     */
	@PersistenceContext (unitName = "LastProjectEJB")
	private EntityManager em;
	
	@EJB
	private RatingConversion conv;
	
    public RatingDAO() {
      
    }

	@Override
	public void create(RatingDTO ratingDTO) {	
		em.persist(conv.fromDTO(ratingDTO));
	}

	@Override
	public void edit(RatingDTO ratingDTO) {
		em.merge(conv.fromDTO(ratingDTO));
	}

	@Override
	public void remove(RatingDTO ratingDTO) {
		Rating r = em.find(Rating.class,
				conv.fromDTO(ratingDTO).getId());
		em.remove(r);
	}

	@Override
	public RatingDTO findById(Object id) {
	
		Rating r = em.find(Rating.class,id);
		RatingDTO rating = conv.fromEntity(r);
		return rating;
	}

	@Override
	public List<RatingDTO> getAll() {
		List<Rating> ratingList = (List<Rating>) em.createNamedQuery("Rating.findAll", Rating.class).getResultList();
		List<RatingDTO> ratingDTO = new ArrayList<RatingDTO>();
		
		for(Rating r:ratingList){
			RatingDTO wl = new RatingDTO();
			wl = conv.fromEntity(r);
			ratingDTO.add(wl);
		}
		return ratingDTO;
	}
	
	public List<RatingDTO> getAllByBookId(int id){
		List<Rating> ratingList = (List<Rating>) em.createQuery("SELECT r FROM Rating r where r.book.id =:id ",Rating.class).
				setParameter("id", id).getResultList();
		List<RatingDTO> ratingDTO = new ArrayList<RatingDTO>();
		
		for(Rating r:ratingList){
			RatingDTO wl = new RatingDTO();
			wl = conv.fromEntity(r);
			ratingDTO.add(wl);
		}
		return ratingDTO;
	}

	

	@Override
	public List<RatingDTO> getAllByUserIdAndBookId(int idUser, int idBook) {
		List<Rating> ratingList = (List<Rating>) em
				.createQuery(
						"SELECT r FROM Rating r where r.user.id =:idUser AND r.book.id =:idBook",
						Rating.class).setParameter("idUser", idUser)
				.setParameter("idBook", idBook).getResultList();
		List<RatingDTO> ratingDTO = new ArrayList<RatingDTO>();

		for (Rating r : ratingList) {
			RatingDTO wl = new RatingDTO();
			wl = conv.fromEntity(r);
			ratingDTO.add(wl);
		}
		return ratingDTO;
	}


    
}
